//设置基地址
axios.defaults.baseURL = "http://ajax-base-api-t.itheima.net";

//获取元素
const form = document.querySelector("#bookForm");
const tb = document.querySelector("#tb");

//进入页面渲染dom
//考虑到后面需要更新数据将渲染函数封装
const getBookList = () => {
  axios({
    method: "GET",
    url: "/api/getbooks",
  }).then(({ data: res }) => {
    //结构获得需要的数据
    const { data, msg, status } = res;
    if (status !== 200) return alert(msg);

    let htmlStr = "";
    data.forEach((item) => {
      htmlStr += ` <tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>
        `;
    });
    tb.innerHTML = htmlStr;
  });
};

//删除图书
tb.addEventListener("click", function (e) {
  //通过自定义属性获取id
  //console.log(e.target.dataset.id);
  let id = e.target.dataset.id;

  //发起请求
  axios({
    method: "GET",
    url: "/api/delbook?id=" + id,
  }).then(({ data: res }) => {
    alert(res.msg);
    getBookList();
  });
});

//新增
form.addEventListener("submit", function (e) {
  e.preventDefault();

  const data = serialize(this, { hash: true });

  //发起ajax请求
  axios({
    method: "post",
    url: "/api/addbook",
    data,
  }).then(({ data: res }) => {
    alert(res.msg);
    getBookList();
  });
});

//调用渲染函数
getBookList();
